#include "queryhistorymanager.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QStandardPaths>
#include <QDir>
#include <QDateTime>
#include <QApplication>
#include <QDebug>

QueryHistoryManager::QueryHistoryManager(QObject *parent)
    : QObject(parent)
    , m_initialized(false)
{
}

QueryHistoryManager::~QueryHistoryManager()
{
    if (m_database.isOpen()) {
        m_database.close();
    }
}

bool QueryHistoryManager::initialize(const QString &databasePath)
{
    if (m_initialized) {
        return true;
    }
    
    m_databasePath = databasePath;
    if (m_databasePath.isEmpty()) {
        m_databasePath = getDefaultDatabasePath();
    }
    
    // 确保目录存在
    QFileInfo fileInfo(m_databasePath);
    QDir dir;
    if (!dir.exists(fileInfo.absolutePath())) {
        if (!dir.mkpath(fileInfo.absolutePath())) {
            qWarning() << "Failed to create directory for query history database:" << fileInfo.absolutePath();
            return false;
        }
    }
    
    // 创建数据库连接
    m_database = QSqlDatabase::addDatabase("QSQLITE", "query_history_connection");
    m_database.setDatabaseName(m_databasePath);
    
    if (!m_database.open()) {
        qWarning() << "Failed to open query history database:" << m_database.lastError().text();
        return false;
    }
    
    // 创建表
    if (!createTables()) {
        return false;
    }
    
    m_initialized = true;
    return true;
}

void QueryHistoryManager::addQuery(const QString &query, const QString &databaseName)
{
    if (!m_initialized || query.trimmed().isEmpty()) {
        return;
    }
    
    QSqlQuery sqlQuery(m_database);
    sqlQuery.prepare("INSERT INTO query_history (query, timestamp, database_name) VALUES (?, ?, ?)");
    sqlQuery.addBindValue(query);
    sqlQuery.addBindValue(QDateTime::currentDateTime());
    sqlQuery.addBindValue(databaseName);
    
    if (!sqlQuery.exec()) {
        qWarning() << "Failed to add query to history:" << sqlQuery.lastError().text();
        return;
    }
    
    emit historyUpdated();
}

QList<QueryHistoryItem> QueryHistoryManager::getRecentQueries(int count) const
{
    QList<QueryHistoryItem> result;
    
    if (!m_initialized) {
        return result;
    }
    
    QSqlQuery sqlQuery(m_database);
    sqlQuery.prepare("SELECT id, query, timestamp, database_name FROM query_history ORDER BY timestamp DESC LIMIT ?");
    sqlQuery.addBindValue(count);
    
    if (!sqlQuery.exec()) {
        qWarning() << "Failed to retrieve query history:" << sqlQuery.lastError().text();
        return result;
    }
    
    while (sqlQuery.next()) {
        QueryHistoryItem item;
        item.id = sqlQuery.value(0).toInt();
        item.query = sqlQuery.value(1).toString();
        item.timestamp = sqlQuery.value(2).toDateTime();
        item.databaseName = sqlQuery.value(3).toString();
        result.append(item);
    }
    
    return result;
}

QList<QueryHistoryItem> QueryHistoryManager::searchQueries(const QString &searchTerm) const
{
    QList<QueryHistoryItem> result;
    
    if (!m_initialized || searchTerm.isEmpty()) {
        return result;
    }
    
    QSqlQuery sqlQuery(m_database);
    sqlQuery.prepare("SELECT id, query, timestamp, database_name FROM query_history WHERE query LIKE ? ORDER BY timestamp DESC LIMIT 100");
    sqlQuery.addBindValue("%" + searchTerm + "%");
    
    if (!sqlQuery.exec()) {
        qWarning() << "Failed to search query history:" << sqlQuery.lastError().text();
        return result;
    }
    
    while (sqlQuery.next()) {
        QueryHistoryItem item;
        item.id = sqlQuery.value(0).toInt();
        item.query = sqlQuery.value(1).toString();
        item.timestamp = sqlQuery.value(2).toDateTime();
        item.databaseName = sqlQuery.value(3).toString();
        result.append(item);
    }
    
    return result;
}

bool QueryHistoryManager::clearHistory()
{
    if (!m_initialized) {
        return false;
    }
    
    QSqlQuery sqlQuery(m_database);
    if (!sqlQuery.exec("DELETE FROM query_history")) {
        qWarning() << "Failed to clear query history:" << sqlQuery.lastError().text();
        return false;
    }
    
    emit historyUpdated();
    return true;
}

int QueryHistoryManager::historyCount() const
{
    if (!m_initialized) {
        return 0;
    }
    
    QSqlQuery sqlQuery(m_database);
    if (!sqlQuery.exec("SELECT COUNT(*) FROM query_history")) {
        qWarning() << "Failed to get query history count:" << sqlQuery.lastError().text();
        return 0;
    }
    
    if (sqlQuery.next()) {
        return sqlQuery.value(0).toInt();
    }
    
    return 0;
}

bool QueryHistoryManager::createTables()
{
    QSqlQuery sqlQuery(m_database);
    QString createTableQuery = R"(
        CREATE TABLE IF NOT EXISTS query_history (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            query TEXT NOT NULL,
            timestamp DATETIME NOT NULL,
            database_name TEXT
        )
    )";
    
    if (!sqlQuery.exec(createTableQuery)) {
        qWarning() << "Failed to create query history table:" << sqlQuery.lastError().text();
        return false;
    }
    
    // 创建索引以提高查询性能
    QString createIndexQuery = "CREATE INDEX IF NOT EXISTS idx_query_history_timestamp ON query_history (timestamp DESC)";
    if (!sqlQuery.exec(createIndexQuery)) {
        qWarning() << "Failed to create index on query history table:" << sqlQuery.lastError().text();
        return false;
    }
    
    return true;
}

QString QueryHistoryManager::getDefaultDatabasePath() const
{
    QString appDataPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    if (appDataPath.isEmpty()) {
        appDataPath = QDir::homePath() + "/.dbtool";
    }
    
    QDir dir(appDataPath);
    if (!dir.exists()) {
        dir.mkpath(appDataPath);
    }
    
    return appDataPath + "/query_history.db";
}